import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'Player.dart';

class SwipeCard extends StatefulWidget {
  SwipeCard({
    required this.footStr,
    required this.data,
  });
  final String footStr;
  final Map data;

  @override
  _SwipeCardState createState() => _SwipeCardState();
}

class _SwipeCardState extends State<SwipeCard> {
  buildTransTextList(){
    List<TextSpan> transList = [];
    if (widget.data["trans"] != null && widget.data["trans"] != '' && widget.data["trans"] != 'null') {
      var transDatas = json.decode(widget.data["trans"]);
      for(var item in transDatas) {
        transList.add(TextSpan(text: item["pos"] != null ? item["pos"].toString() : '',style: const TextStyle(color: Colors.black54,fontSize: 16)));
        transList.add(TextSpan(text: (item["pos"] != null && item["pos"] != '') ?'.':'',style: TextStyle(color: Colors.black54,fontSize: 16)));
        transList.add(TextSpan(text: item["tranCn"] != null ? item["tranCn"].toString() : '',style: const TextStyle(color: Colors.black54,fontSize: 16)));
        transList.add(TextSpan(text: (item["tranCn"] != null && item["tranCn"] != '')? ' ':'',style: TextStyle(color: Colors.black54,fontSize: 16)));
      }
    }
    return transList;
  }
  getHelpText() {
    if (widget.data["helpText"] != null && widget.data["helpText"] != '' && widget.data["helpText"] != 'null'){
      return json.decode(widget.data["helpText"]);
    } else {
      return {
        'default': {"val": "","desc": ""},
        'self': []
      };
    }
  }
  hasDefaultHelpText() {
    Map helpText = getHelpText();
    return (helpText.containsKey('default') && helpText['default'].containsKey('val') && helpText['default']['val'] != '');
  }
  hasSelfHelpText() {
    Map helpText = getHelpText();
    return (helpText.containsKey('self') && helpText['self'].length > 0);
  }

  buildSelfHelpTextList() {
    List<Widget> selfHelpTextList = [];
    if (hasSelfHelpText()) {
      var textList = getHelpText()['self'];
      for(var item in textList) {
        selfHelpTextList.add(
          RichText(
            textAlign: TextAlign.center,
            text: TextSpan(text: item['val'],style: const TextStyle(color: Colors.black54,fontSize: 16)),
          ),
        );
        selfHelpTextList.add(
          const SizedBox(height: 5,)
        );

      }
    }
    return selfHelpTextList;
    // RichText(
    //   textAlign: TextAlign.center,
    //   text: TextSpan(text: getHelpText()['default']['val'],style: const TextStyle(color: Colors.black54,fontSize: 16)),
    // ),
  }
  getSentences() {
    if (widget.data["sentence"] != null && widget.data["sentence"] != '' && widget.data["sentence"] != 'null'){
      return json.decode(widget.data["sentence"]);
    } else {
      return {
        "sentences": [],
        "desc": ""
      };
    }
  }
  hasSentences() {
    Map sentence = getSentences();
    return (sentence.containsKey('sentences') && sentence['sentences'].length > 0);
  }
  buildSentencesList() {
    List<Widget> sentencesList = [];
    if (hasSentences()) {
      var textList = getSentences()['sentences'];
      for(var item in textList) {
        sentencesList.add(
            RichText(
              textAlign: TextAlign.center,
              text: TextSpan(text: item['sContent'],style: const TextStyle(color: Colors.black87,fontSize: 16)),
            )
        );
        sentencesList.add(
            const SizedBox(height: 3,)
        );
        sentencesList.add(
            RichText(
              textAlign: TextAlign.center,
              text: TextSpan(text: item['sCn'],style: const TextStyle(color: Colors.black54,fontSize: 15)),
            )
        );
        sentencesList.add(
            Container(
              margin: const EdgeInsets.fromLTRB(15, 5, 15, 5),
              decoration: const BoxDecoration(
                border:  Border(bottom:BorderSide(width: 0.5,color: Color(0xffe5e5e5)) ),
              ),
            )
        );
      }
    }
    return sentencesList;
  }


  buildTransList() {
    List<Widget> transList = [];
    if (widget.data["trans"] != null && widget.data["trans"] != '' && widget.data["trans"] != 'null') {
      var transDatas = json.decode(widget.data["trans"]);
      for(var item in transDatas) {
        transList.add(
            Container(
                alignment: Alignment.center,
                child: Text.rich(
                    TextSpan(
                        children: [
                          TextSpan(text: item["pos"] != null ? item["pos"].toString() : '',style: const TextStyle(color: Colors.black54,fontSize: 16)),
                          const TextSpan(text: '. ',style: TextStyle(color: Colors.black54,fontSize: 16)),
                          TextSpan(text: item["tranCn"] != null ? item["tranCn"].toString() : '',style: const TextStyle(color: Colors.black54,fontSize: 16)),
                          const TextSpan(text: ' ',style: TextStyle(color: Colors.black54,fontSize: 16)),
                        ]
                    )
                )
            )
        );
      }
    }
    return transList;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment:Alignment.center ,
      children: [

        Container(
          decoration: BoxDecoration(
            color: CupertinoColors.white,
            border: Border.all(color: Colors.black54, width: 1.2),// border
            borderRadius: BorderRadius.circular((5)), // 圆角
          ),
          alignment: Alignment.center,
          child: ListView(
            children: [
              Container(
                padding: const EdgeInsets.fromLTRB(15, 15, 15, 15),
                decoration: const BoxDecoration(
                  color: CupertinoColors.black,
                ),
                alignment: Alignment.center,
                child: Text(widget.data['name'],style: TextStyle(color: Colors.white,fontWeight: FontWeight.w600,fontSize: 30),),
                // color: CupertinoColors.white,
              ),
              SizedBox(height: 10,),
              Container(
                  padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                  alignment: Alignment.center,
                  child: Container(
                      alignment: Alignment.center,
                      child: Text.rich(
                          TextSpan(
                              children: buildTransTextList()
                          )
                      )
                  )
                  // Column( children: buildTransList(), )
              ),
              SizedBox(height: 10,),
              Container(
                padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                alignment: Alignment.center,
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Text('美 ',style: TextStyle(color: Colors.black54,fontSize: 16)),
                      widget.data["usphone"] != null ?Player(
                          text: widget.data["usphone"],
                          src: 'https://dict.youdao.com/dictvoice?audio=' + widget.data["usspeech"],
                          color: Colors.blueGrey,
                          autoplay: false
                      ):const SizedBox(),
                    ]
                ),
                // color: CupertinoColors.white,
              ),
              SizedBox(height: 10,),
              Container(
                padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                alignment: Alignment.center,
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Text('英 ',style: TextStyle(color: Colors.black54,fontSize: 16)),
                      widget.data["ukphone"] != null ?Player(
                          text: widget.data["ukphone"],
                          src: 'https://dict.youdao.com/dictvoice?audio=' + widget.data["ukspeech"],
                          color: Colors.blueGrey,
                          autoplay: false
                      ):const SizedBox(),
                    ]
                )
                // color: CupertinoColors.white,
              ),
              hasDefaultHelpText()?const SizedBox(height: 10,):const SizedBox(),
              hasDefaultHelpText()?Container(
                  padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                  alignment: Alignment.center,
                  child: Container(
                      alignment: Alignment.center,
                      child: RichText(
                        textAlign: TextAlign.center,
                        text: TextSpan(text: getHelpText()['default']['val'],style: const TextStyle(color: Colors.black54,fontSize: 16)),
                      ),
                  )
                // Column( children: buildTransList(), )
              ):const SizedBox(),
              hasSelfHelpText()?const SizedBox(height: 10,):const SizedBox(),
              hasSelfHelpText()?Container(
                  padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                  alignment: Alignment.center,
                  child: Container(
                    alignment: Alignment.center,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: buildSelfHelpTextList(),
                    ),
                  )
                // Column( children: buildTransList(), )
              ):const SizedBox(),
              Container(
                margin: const EdgeInsets.fromLTRB(15, 5, 15, 0),
                // padding: const EdgeInsets.fromLTRB(15, 0, 15, 5),
                decoration: const BoxDecoration(
                  border:  Border(bottom:BorderSide(width: 1,color: Color(0xffe5e5e5)) ),
                ),
              ),
              hasSentences()?const SizedBox(height: 10,):const SizedBox(),
              hasSentences()?Container(
                  padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                  alignment: Alignment.center,
                  child: Container(
                    alignment: Alignment.center,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: buildSentencesList()
                    ),
                  )
                // Column( children: buildTransList(), )
              ):const SizedBox(),
              SizedBox(height: 50,),
            ],
          ),
          // color: CupertinoColors.white,
        ),
        Positioned(
          bottom: 1, //距离顶部27px
          left: 1,
          right: 1,
          child: Container(
            padding: const EdgeInsets.fromLTRB(0, 5, 0, 12),
            child: Column(
              children: [
                Container(
                  margin: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                  decoration: const BoxDecoration(
                    border:  Border(bottom:BorderSide(width: 1,color: Color(0xffe5e5e5)) ),
                  ),
                ),
                Text(widget.footStr)
              ],
            ),
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(5),
                bottomRight: Radius.circular(5),
              ),
            ),
          ),
        )
      ],
    );
  }
}
